import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'config/app_theme.dart';
import 'providers/article_provider.dart';
import 'providers/audio_provider.dart';
import 'screens/main_screen.dart';
import 'screens/login_screen.dart';
import 'utils/storage_util.dart';
import 'services/http_service.dart';

// 全局导航 key
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化本地存储
  await StorageUtil.init();
  
  // 设置状态栏
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ),
  );
  
  // 设置登录过期回调
  HttpService().setLoginExpiredCallback(() {
    // 跳转到登录页
    navigatorKey.currentState?.pushAndRemoveUntil(
      MaterialPageRoute(builder: (context) => const LoginScreen()),
      (route) => false,
    );
  });
  
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => ArticleProvider()),
        ChangeNotifierProvider(create: (_) => AudioProvider()),
      ],
      child: MaterialApp(
        title: 'TZAI 投资风向',
        debugShowCheckedModeBanner: false,
        theme: AppTheme.darkTheme,
        navigatorKey: navigatorKey,
        home: _getInitialScreen(),
      ),
    );
  }
  
  // 根据登录状态决定初始页面
  Widget _getInitialScreen() {
    // 检查是否已登录
    final isAuthenticated = StorageUtil.isAuthenticated();
    return isAuthenticated ? const MainScreen() : const LoginScreen();
  }
}
